from abc import ABC

from tornado.websocket import WebSocketHandler, WebSocketClosedError
import time
from libs.encode import Encode

clients = dict()


class WebSocketServerHandler(WebSocketHandler, ABC):
    token = None
    file = None

    def open(self, *args, **kwargs):
        self.token = self.get_arguments("token")[0]
        print("connect token:", self.token)
        if (self.token is None) or (Encode.check(self.token) is False):
            self.close(1002, "token is none or invalid")
            return
        self.file = self.create_file()
        clients[self.token] = {"token": self.token, "object": self}
        self.set_nodelay(True)
        pass

    def on_message(self, message):
        if type(message) == str:
            print("string message, ignore...")
        else:
            print("byte data， len=" + str(len(message)))
            if self.file is not None:
                self.file.write(message[3:])
            else:
                print("target client is closed")
                self.send_end(self.pair_token)

    def on_close(self):
        if self.file is not None:
            self.file.close()
        if self.token in clients:
            del clients[self.token]
            print("client %s is closed" % self.token)

    def check_origin(self, origin):
        return True

    def create_file(self):
        prefix = self.token[:5]
        ct = time.time()
        file_name = prefix.replace("/", "_") + "_" + str(ct) + ".h264"
        path = 'static/video/{}'.format(file_name)
        return open(path, "wb")
